package com.sajus.web.billing.admin.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.sajus.billing.client.delegate.BusinessDelegateFactory;
import com.sajus.billing.client.dto.AccountDTO;
import com.sajus.billing.client.dto.BillDTO;
import com.sajus.billing.client.dto.ServiceDTO;
import com.sajus.web.billing.ejb.bean.SajusBillingTimerBean;

/**
 * Acts as a Struts 2 controller that responds
 * to a user action by setting the value
 * of the Message model class, and returns a String 
 * result.
 * @author Bruce Phillips
 *
 */
public class RunBillingAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	
	
	/*
	 * Creates the MessageStore model object and 
	 * returns success.  The MessageStore model
	 * object will be available to the view.
	 * (non-Javadoc)
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	public String execute() throws Exception {
		String paramValue = ServletActionContext.getRequest().getParameter("runcharge");
		
		if ( paramValue != null ){
			try {
				Logger.getLogger( SajusBillingTimerBean.class ).info( "Starting doing charging for usage " + new Date()); 
				BusinessDelegateFactory.getInstance().getServiceTypeManager().doUsageBilling();
				
			} catch (NamingException e) {
				e.printStackTrace();
			} catch ( Exception e ){
				System.out.println("Do Usage failed " + e.getMessage() );
			}
			
		}
		
		//Grab all accounts
		List<AccountDTO> accounts = BusinessDelegateFactory.getInstance().getAccountManager().getAccounts();
		
		for ( AccountDTO acc : accounts ){
			
			System.out.println("Running Billing for account " + acc.getId() );
			// don't need to do for children since we're doing all accounts;
			BusinessDelegateFactory.getInstance().getAccountManager().createBill( acc );
			// Set new billing date for account;
			BusinessDelegateFactory.getInstance().getAccountManager().setBillFeeAmount( acc );
		}
		return SUCCESS;
	}
	
}
